/*
 * Copyright (c) $today.year-Now http://www.zxpnet.com All rights reserved.
 */

package com.zxp.security.controller;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import com.zxp.common.core.security.properties.SecurityProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @author: shollin
 * @date: 2021/7/4/004 17:54
 */
@RestController
@RequiredArgsConstructor
@Slf4j
public class HelloController {

    private final SecurityProperties securityProperties;

    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping("/admin/hello")
    public String admin() {
        return "admin";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "user";
    }

    // jwt token的话，@AuthenticationPrincipal UserDetails拿不到
    @GetMapping("/me")
    public Object me(Authentication user, HttpServletRequest request) throws Exception {

        String authorization = request.getHeader(Header.AUTHORIZATION.getValue());
        if(StrUtil.isNotBlank(authorization)){
            String token = StrUtil.subAfter(authorization,"bearer ", true);
            Claims claims = Jwts.parser().setSigningKey(securityProperties.getJwt().getSecret().getBytes(CharsetUtil.UTF_8))
                    .parseClaimsJws(token).getBody();
            Object author = claims.get("author");
            log.info("作者："+author);
        }
        return user;
    }
}
